package com.example.demo.service.impl;

import com.example.demo.dto.OrderStatisticsDTO;
import com.example.demo.entity.Order;
import com.example.demo.mapper.OrderMapper;
import com.example.demo.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private VoicePlanServiceImpl voicePlanServiceImpl;

    //创建订单
    public Order createOrder(int userId, int serviceId, double amount) {
        Order order = new Order();
        order.setUserId(userId);
        order.setServiceId(serviceId);
        order.setOrderNo(generateOrderNo());
        order.setAmount(amount);
        order.setDuration(getServiceDuration(serviceId));
        order.setStatus(1);
        order.setCreateTime(getCurrentTime());
        order.setUpdateTime(getCurrentTime());
        orderMapper.insertOrder(order);
        return order;
    }
    //更新订单状态通过订单号
    public void updateOrderStatusByOrderNo(String orderNo) {
        Order order = orderMapper.getOrderByOrderNo(orderNo);
        if (order == null) {
            throw new RuntimeException("订单不存在，订单号: " + orderNo);
        }
        orderMapper.updateOrderStatusByOrderNo(orderNo,2,getCurrentTime());
    }
    //更新订单状态
    public boolean updateOrderStatus(int id, int status) {
        String updateTime = getCurrentTime();
        return orderMapper.updateOrderStatus(id, status, updateTime) > 0;
    }
    //获取订单状态
    public int getOrderStatus(String orderNo) {
        return orderMapper.getStatusByOrderNo(orderNo);
    }

    //获取购买时间
    public String getOrderPayTime(String orderNo) {
        return orderMapper.getPayTimeByOrderNo(orderNo);
    }
    public Order getOrder(String orderNo) {
        return orderMapper.getOrderByOrderNo(orderNo);
    }
    /**
     * 以下为生成订单号的前置函数
     */

    // 使用AtomicInteger保证线程安全
    private static final AtomicInteger sequence = new AtomicInteger(0);

    // 最大序列号，达到最大值后重置
    private static final int MAX_SEQUENCE = 9999;

    // 日期格式
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");

    // 随机数生成器
    private static final Random RANDOM = new Random();
    /**
     * 生成订单号
     * 格式：时间戳(14位) + 随机数(2位) + 序列号(4位)
     * 示例：20231108123045012345
     * @return 生成的订单号
     */
    public String generateOrderNo() {
        // 1. 获取当前时间戳
        String timeStamp = DATE_FORMAT.format(new Date());

        // 2. 生成随机数(2位)
        int randomNum = RANDOM.nextInt(90) + 10; // 10-99之间的随机数

        // 3. 获取序列号并递增
        int seq = sequence.incrementAndGet();
        if (seq > MAX_SEQUENCE) {
            sequence.set(0);
            seq = sequence.incrementAndGet();
        }

        // 4. 组合成订单号
        return timeStamp + String.format("%02d", randomNum) + String.format("%04d", seq);
    }
    //获取服务时长
    public double getServiceDuration(int id)
    {
        return voicePlanServiceImpl.getDuration(id);
    }

    //获取时间
    public String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    //判断订单是否支付
    public boolean isOrderPaid(String orderNo) {
        int status = getOrderStatus(orderNo);
        return status==2;//订单状态为2时为支付
    }

    //发起退款请求

    @Override
    public boolean refundOrder(String orderNo) {
        orderMapper.refundOrderStatusByOrderNo(orderNo, 4, getCurrentTime());
        return true;
    }

    //返回订单统计信息
    @Override
    public OrderStatisticsDTO getOrderStatistics(int userId) {
        OrderStatisticsDTO stats = new OrderStatisticsDTO();
        //待付款
        stats.setPendingPaymentCount(orderMapper.countByStatus(userId, 1));
        //已付款
        stats.setPaidCount(orderMapper.countByStatus(userId, 2));
        //已取消
        stats.setCancelledCount(orderMapper.countByStatus(userId, 3));
        //退款中
        stats.setRefundingCount(orderMapper.countByStatus(userId, 4));
        //已取消
        stats.setCancelledCount(orderMapper.countByStatus(userId, 5));
        //已退款
        stats.setRefundedCount(orderMapper.countByStatus(userId, 6));
        return stats;
    }

    @Override
    public List<Order> getOrderList(int userId, Integer status, Double minAmount, Double maxAmount, String startTime, String endTime, int pageNum, int pageSize) {
        //起始数
        int offset = (pageNum - 1) * pageSize;

        return orderMapper.selectOrderList(userId, status, minAmount, maxAmount, startTime, endTime, offset, pageSize);
    }

    @Override
    public List<Order> getOrders(int userId, Integer status, int pageNum, int pageSize){
        int offset = (pageNum - 1) * pageSize;
        return orderMapper.selectOrders(userId, status, offset, pageSize);
    }

    @Override
    public List<Order> getAllOrders(int userId){
        return orderMapper.selectAllOrders(userId);
    }

    @Override
    public Order getOrderById(int orderId) {
        return orderMapper.selectById(orderId);
    }

    @Override
    public List<Order> searchOrdersByServiceName(int userId, String serviceName) {
        return orderMapper.searchByServiceName(userId, serviceName);
    }
}